#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
 Source file
 File name: svi.py
 Creation date: 11-09-2011
 Author: dassier

'''

import pysvn
import getpass
import sys
import os
import subprocess
import getopt
from svi.core.logging import LogMsg
from svi.core.config import Config
from svi.command.alias  import ReplaceAlias
from svi.command.basecmd  import Error


# Constantes definition
VERSION = u"0.1"
CONF_FILE = u".svirc"
SVN_PROG = "svn"

#############################################################
def get_login(realm, username, may_save):
    ''' Callback use by svn client
    to identify user
    '''

    msg = LogMsg()

    if not username:
        msg.info(u'User : ')
        username = sys.stdin.readline().strip()
        if len(username) == 0:
            return False, '', '', False
    msg.info(u"User: '%s'" % username)
    password = getpass.getpass(u'Enter password :').strip()
    return True, username, password, True

#############################################################
def usage():
    msg = LogMsg()
    msg.banner()
    msg.help('''Usage: svi <command> <command arguments>...

List of available command:
    alias
    tag

Type 'svi help <command> for more information
''')

#############################################################
def main():

    ''' Main function
    '''


    # Check program argument
    # if no argument or
    # if first arguemnt is 'help' or '-h' or '--help'
    # display usage information
    if len(sys.argv) == 1 or sys.argv[1] == 'help' \
            or sys.argv[1] == '-h' or sys.argv[1] == '--help':
                usage()
                return True

    # OK, there's arguments
    # Create logging mechanism
    msg = LogMsg()

    # Now check for configuration file
    if os.getenv('HOME') is None:
        # $HOME is not defined !
        msg.error(u'$HOME not found, cannot get configuration file')
        return True
    conf_full_path = os.getenv(u'HOME') + os.sep + CONF_FILE

    cfg = Config(conf_full_path)
    client = pysvn.Client()
    client.callback_get_login = get_login

    # First argument shall be svi command
    # svi command are developp in command/<command>.py file
    cmd_name = sys.argv[1]
    #import pdb; pdb.set_trace()
    # If command is not 'alias', replace alias in parameter
    if cmd_name != "alias":
        func = ReplaceAlias(cfg)
        cmd_arg = map(func.replace, sys.argv[1:])  
    else:
        cmd_arg = sys.argv[1:] 

    try:
        module = __import__("svi.command." + cmd_name, fromlist=["command"])

    except ImportError:
        # Command not found
        # Lets assume it is an svn command
        # So calls svn client with whole command line argument
        msg.info('"%s" is not a svi internal command' % cmd_name)
        msg.info("Lets call svn directly with full command line as argument")
        svn_arg = []
        svn_arg.append(SVN_PROG)
        svn_arg += cmd_arg
        msg.info('Command line is "%s"\n' % " ".join(svn_arg))
        return subprocess.call(svn_arg)

    cmd=[]
    verbose = False
    # OK, command is found
    for index in range(len(cmd_arg)):
        if cmd_arg[index] == '-v':
            verbose = True
        else:
            cmd.append(cmd_arg[index])   
    command = module.command(cmd[1:], client, cfg) 
    try:
        command.run()
    except Error, error:
        if verbose is False:
            print "Error: %s" % str(error)
            return False
        else:
            raise
# Add verbose ici et recption de tout les message par le except
# remove param debugging dans basecmd, alias et tag
    return False

if __name__ == '__main__':
    sys.exit(main())
